package com.weibo.boot.springbootlearn.service.job;

import com.alibaba.fastjson.JSON;
import com.weibo.boot.springbootlearn.dao.mapper.FundAllMapper;
import com.weibo.boot.springbootlearn.dao.mapper.FundMapper;
import com.weibo.boot.springbootlearn.dao.model.Fund;
import com.weibo.boot.springbootlearn.dao.model.FundAll;
import com.weibo.boot.springbootlearn.model.ResultDto;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author panda
 * @version Id: DaydayFundDataJob, v 0.1 2020/11/22 3:30 下午 Exp $
 * @description
 */
@Component
@Slf4j
public class DayDayFundAllDataJob {

    @Resource
    private FundAllMapper fundAllMapper;
    private OkHttpClient client = new OkHttpClient();

    // Request URL: http://fund.eastmoney.com/data/FundGuideapi.aspx?dt=4&sd=&ed=&sc=3y&st=desc&pi=3&pn=20&zf=diy&sh=list&rnd=0.5011507759385259
    @Scheduled(cron = "30 24 17 * * ? ")
    // @Scheduled(cron = "0/20 * * * * ?")
    public void process() throws Exception {
        log.info("process");
        Integer pageIndex = 1;
        Integer pageSize = 20;
        Integer allPages = 1;

        do {
            try {
                String url = String.format("http://fund.eastmoney.com/data/FundGuideapi.aspx?dt=4&sd=&ed=&sc=3y&st=desc&pi=%s&pn=%s&zf=diy&sh=list&rnd=0.5011507759385259", pageIndex, pageSize);
                Request request = new Request.Builder()
                        .get()
                        .url(url)
                        .build();

                String string = client.newCall(request).execute().body().string();
                String json = StringUtils.removeStart(string, "var rankData =");
                ResultDto resultDto = JSON.parseObject(json, ResultDto.class);
                allPages = resultDto.getAllPages();
                save(resultDto);
            } catch (Exception e) {
                log.error("{}", e);
            }

            TimeUnit.SECONDS.sleep(new Random().nextInt(10));
        } while (pageIndex++ < allPages);
    }

    private void save(ResultDto resultDto) throws ParseException {
        for (String data : resultDto.getDatas()) {
            try {
                log.info("{}", data);
                FundAll fund = goog(data);
                fundAllMapper.insertSelective(fund);
            } catch (ParseException e) {
                log.error(JSON.toJSONString(resultDto), e);
            }
        }
    }

    private FundAll goog(String data) throws ParseException {
        List<String> collect = Arrays.stream(data.split(",")).collect(Collectors.toList());
        // 009147,建信新能源行业股票,JXXNYHYGP,股票型,,
        // -0.31,6.07,34.77,,,
        // ,,,,1,
        // 2020-11-20,1.3955,2.47,1,0.15%,
        // 100,1,1.50%,0.15%
        FundAll fund = new FundAll();
        fund.setCode(collect.get(0));
        fund.setName(collect.get(1));
        fund.setType(collect.get(3));

        fund.setFee(collect.get(collect.size() - 1));

        fund.setJz(collect.get(16));
        fund.setInRate(collect.get(17));

        fund.setWeek(collect.get(5));
        fund.setMonth(collect.get(6));
        fund.setThreeMonth(collect.get(7));
        fund.setSixMonth(collect.get(8));
        fund.setThisYear(collect.get(9));
        fund.setOneYear(collect.get(10));
        fund.setTwoYear(collect.get(10));
        fund.setThreeYear(collect.get(11));
        fund.setDataDate(DateUtils.parseDate(collect.get(15), "yyyy-MM-dd"));
        return fund;
    }
}
